package NewTmas.Listeners;

import NewTmas.FramesandPanels.JobGraphPanel;
import NewTmas.Graphs.GraphViz;
import NewTmas.Graphs.GraphVizGraph;
import net.sf.ghost4j.converter.ConverterException;
import net.sf.ghost4j.converter.PDFConverter;
import net.sf.ghost4j.document.DocumentException;
import net.sf.ghost4j.document.PSDocument;
import org.apache.commons.io.IOUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: abhatnag
 * Date: 8/9/11
 * Time: 3:38 PM
 * To change this template use File | Settings | File Templates.
 */
public class PrintGraphListener implements ActionListener
{

    String jobName;
    List<JobGraphPanel> graphPanelList;
    JobGraphPanel graphPanel;

    public PrintGraphListener(String str, List<JobGraphPanel> graphPanelList)
    {
        this.jobName = str;
        this.graphPanelList = graphPanelList;
    }

    public void actionPerformed(ActionEvent e)
    {

        for (int i = 0; i < graphPanelList.size(); i++)
        {

            if (graphPanelList.get(i).job.equalsIgnoreCase(jobName))
            {

                graphPanel = graphPanelList.get(i);
                break;
            }

        }
        GraphVizGraph graphViz = (GraphVizGraph) graphPanel.getGraphObj();

        String str = graphViz.graphStr;

        // removing "color=something" from the DOT  to show graphs irrespective of status because we are using the same graph object
        String[] strs = str.split("\\n");
        ArrayList<String> dotStr = new ArrayList<String>();
        for (int i = 0; i < strs.length; i++)
        {
            if (!strs[i].contains("color"))
            {

                dotStr.add(strs[i]);
            }


        }


        generatePDF(dotStr, jobName);


    }

    private void generatePDF(ArrayList<String> graphStr, String jobName)
    {
        /*Save PDF Files for generated graphs to disk*/
        String type = "ps";
        File outPsFile = new File(System.getProperty("TEMP_DIR") + File.separator + jobName + "." + type);


//        InputStream in=null;
        FileOutputStream outPdfStream = null;
        try
        {
            writeGraphToPs(graphStr, type, outPsFile);
//            in = new FileInputStream(outPsFile);
            File pdfFile = new File(System.getProperty("TEMP_DIR") + File.separator + jobName + "." + "pdf");

            PSDocument document = new PSDocument();
            document.load(outPsFile);

            outPdfStream = new FileOutputStream(pdfFile);

            PDFConverter converter = new PDFConverter();
            //set options
            converter.setPDFSettings(PDFConverter.OPTION_PDFSETTINGS_PREPRESS);
            //convert
            converter.convert(document, outPdfStream);

            outPdfStream.close();

            Desktop dt = Desktop.getDesktop();
            dt.open(pdfFile);
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(null, "Problem creating/launching the pdf file" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } catch (ConverterException e)
        {
            JOptionPane.showMessageDialog(null, "Problem creating the pdf file" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (DocumentException e)
        {
            JOptionPane.showMessageDialog(null, "Problem creating the pdf file" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        finally
        {
            IOUtils.closeQuietly(outPdfStream);
        }
    }

    private void writeGraphToPs(ArrayList<String> graphStr, String type, File outPsFile) throws IOException
    {
        GraphViz gv = new GraphViz();

        for (int i = 0; i < graphStr.size(); i++)
        {
            System.out.print(graphStr.get(i));
            gv.addln(graphStr.get(i));
        }
        final String dotSource = gv.getDotSource();
        final byte[] img = gv.getGraph(dotSource, type);
        if (gv.writeGraphToFile(img, outPsFile) == -1)
        {
            throw new IOException("failed in writeGraphToFile for " + outPsFile.getAbsolutePath());
        }
    }

}
